<template>
  <div class="toGrassrootsUnit app-container">
    <el-row>
      <div class="w-200px mr-15px">
        <el-select
          placeholder="申请单位"
          v-model="searchWord.createByOrgId"
          @change="getList"
          clearable
          :disabled="disabledDept"
        >
          <el-option
            v-for="item in deptList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>

      <div class="w-300px mr-15px">
        <el-date-picker
          v-model="timeArray"
          type="daterange"
          range-separator="至"
          start-placeholder="创建日期起"
          end-placeholder="创建日期止"
          value-format="YYYY-MM-DD"
          style="width: 100%"
          @change="changeTime"
          clearable
        />
      </div>

      <div class="w-200px mr-15px">
        <el-select
          placeholder="状态"
          v-model="searchWord.approvalFlag"
          @change="getList"
          clearable
        >
          <el-option value="审批中" label="审批中"></el-option>
          <el-option value="审批通过" label="审批通过"></el-option>
        </el-select>
      </div>

      <div class="w-200px mr-15px">
        <el-input
          v-model="searchWord.userNames"
          placeholder="员工姓名"
          @change="getList"
          clearable
        ></el-input>
      </div>

      <el-button type="primary" icon="Search" @click="getList"> 查询</el-button>
      <el-button icon="Refresh" @click="resetForm">重置</el-button>
    </el-row>

    <el-row class="my-15px">
      <el-button type="primary" icon="Plus" @click="addRow"> 新增</el-button>
      <el-button
        type="primary"
        plain
        icon="Edit"
        @click="editRow"
        :disabled="isDisabled"
      >
        修改</el-button
      >
      <el-button
        type="primary"
        plain
        icon="Search"
        @click="detailRow"
        :disabled="isDisabled"
        >查看</el-button
      >
      <el-button
        type="primary"
        plain
        icon="Delete"
        :disabled="isDisabled"
        @click="deleteRow"
      >
        删除</el-button
      >
      <el-button type="primary" plain icon="Upload" @click="showUpload = true">
        上传</el-button
      >
      <el-button
        type="primary"
        plain
        icon="Download"
        @click="exportData"
        v-loading="exportBtnLoading"
      >
        导出</el-button
      >
      <el-button
        type="primary"
        plain
        icon="Star"
        :disabled="isDisabled"
        @click="approve"
        v-hasPermi="['grassroots:unit:approve']"
        >审批</el-button
      >
      <el-button type="primary" plain icon="MagicStick" @click="gotoStatistics"
        >统计
      </el-button>
    </el-row>

    <div>
      <el-table
        :data="dataList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column type="index" width="55" label="序号"></el-table-column>
        <el-table-column
          prop="approvalFlag"
          label="状态"
          width="80"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="deptName"
          label="到访分公司名称"
          align="center"
          width="200"
        />
        <el-table-column
          prop="userNames"
          label="领导名称"
          align="center"
          width="150"
        >
        </el-table-column>

        <el-table-column
          prop="visitTimeBegin"
          label="到访日期开始"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="visitTimeEnd"
          label="到访日期结束"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="outlets"
          label="网点名称"
          align="center"
          width="150"
        >
        </el-table-column>
        <el-table-column
          label="详细内容"
          prop="remark"
          align="center"
          min-width="150"
        ></el-table-column>
        <el-table-column
          prop="createByOrgName"
          label="申请单位"
          align="center"
          width="150"
        />
        <el-table-column
          prop="createBy"
          label="创建人"
          align="center"
          width="100"
        />
        <el-table-column
          prop="createTime"
          label="创建日期"
          align="center"
          width="120"
        />
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="searchWord.pageNum"
        v-model:limit="searchWord.pageSize"
        @pagination="getList"
      />
    </div>
    <Modal
      v-model="showModal"
      @refresh="getList"
      :modalType="modalType"
      :deptList="deptList"
      :formId="selectRow.formId"
    />

    <el-dialog
      title="导入文件"
      v-model="showUpload"
      append-to-body
      @close="closeUpload"
    >
      <el-upload
        ref="uploadRef"
        class="w-full"
        :show-file-list="true"
        @change="fileChange"
        accept=".xlsx, .xls"
        :auto-upload="false"
        :limit="1"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="downloadTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div>
          <el-button type="primary" @click="uploadFiles">确定</el-button>
          <el-button @click="cancelupload">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ToGrassrootsUnit">
import Modal from './Modal'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import {
  getUnitList,
  deleteUnitList,
  updateUnitList,
  uploadUnitList,
  exportUnitList
} from '@/api/toGrassrootsUnit'
const commonStore = useCommonStore()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const router = useRouter()

const deptList = ref([])
const disabledDept = ref(false)
async function init() {
  const list = await commonStore.getCompanyData()
  deptList.value = list[0].children
  if (userStore.userInfo.orgId != 484) {
    deptList.value = list
    searchWord.value.createByOrgId = userStore.userInfo.orgId
    disabledDept.value = true
  }

  getList()
}

const total = ref(0)
const dataList = ref([])
const searchWord = ref({ pageNum: 1, pageSize: 10 })
const loading = ref(false)
function getList() {
  Object.keys(searchWord.value).forEach(key => {
    if (!searchWord.value[key]) {
      delete searchWord.value[key]
    }
  })

  loading.value = true
  getUnitList(searchWord.value)
    .then(res => {
      dataList.value = res.data.records
      total.value = res.data.total
    })
    .finally(() => {
      loading.value = false
    })
}

function resetForm() {
  searchWord.value = { pageNum: 1, pageSize: 10 }
  timeArray.value = null
  getList()
}

const timeArray = ref(null)
// 选择到访时间
function changeTime(val) {
  if (val) {
    searchWord.value.searchTimeBegin = val[0]
    searchWord.value.searchTimeEnd = val[1]
  } else {
    searchWord.value.searchTimeBegin = null
    searchWord.value.searchTimeEnd = null
  }
  getList()
}

const showModal = ref(false)
const modalType = ref('新增')
function addRow() {
  showModal.value = true
  modalType.value = '新增'
}
function editRow() {
  if (selectRow.value.approvalFlag === '审批通过') {
    proxy.$modal.msgWarning('审批通过,无法编辑')
    return
  }
  showModal.value = true
  modalType.value = '编辑'
}

function detailRow() {
  showModal.value = true
  modalType.value = '查看详情'
}

function approve() {
  if (selectRow.value.approvalFlag !== '审批中') {
    proxy.$modal.msgWarning('审批状态不是审批中，无法审批')
    return
  }
  proxy.$modal.confirm('是否确定要审批通过吗').then(async () => {
    const res = await updateUnitList({
      formId: selectRow.value.formId,
      approvalFlag: '审批通过'
    })
    if (res.code === 200) {
      proxy.$modal.msgSuccess('审批成功')
      getList()
    }
  })
}

function deleteRow() {
  if (selectRow.value.approvalFlag === '审批通过') {
    proxy.$modal.msgWarning('审批通过')
    return
  }
  proxy.$modal
    .confirm('是否确定要删除吗')
    .then(async () => {
      const res = await deleteUnitList({ formId: selectRow.value.formId })
      if (res.code === 200) {
        proxy.$modal.msgSuccess('删除成功')
        getList()
      }
    })
    .catch(() => {})
}

// 导入
const showUpload = ref(false)
const uploadfile = ref()
function fileChange(file, files) {
  console.log(file, files)
  if (!file) {
    return
  }
  const index = file.raw.name.lastIndexOf('.')
  const fileType = file.raw.name.slice(index + 1)
  if (fileType != 'xlsx' && fileType != 'xls') {
    proxy.$modal.msgError('请上传xlsx或xls格式的文件')
    return
  }
  uploadfile.value = file.raw
}

function closeUpload() {
  showUpload.value = false
}

function downloadTemplate() {
  proxy.downLoadByUrl(
    '/system/leadervisit/exportformtemplate',
    {},
    '导入模板.xlsx'
  )
}

const exportBtnLoading = ref(false)
function exportData() {
  proxy.$modal.confirm('是否导出当前列表').then(() => {
    exportBtnLoading.value = true
    const params = { ...searchWord.value }
    delete params.pageNum
    delete params.pageSize

    exportUnitList(params)
      .then(res => {
        const a = document.createElement('a')
        const data = new Blob([res])
        const url = window.URL.createObjectURL(data)
        a.href = url
        a.download = '网点视察单列表数据.xlsx'
        a.click()
        window.URL.revokeObjectURL(url)
      })
      .finally(() => {
        exportBtnLoading.value = false
      })
  })
}

function uploadFiles() {
  // proxy.$refs['uploadRef'].submit()
  if (uploadfile.value) {
    let formData = new FormData()
    formData.append('file', uploadfile.value)
    uploadUnitList(formData)
      .then(res => {
        proxy.$modal.msgSuccess('导入成功')
        showUpload.value = false
      })
      .catch(() => {
        proxy.$refs['uploadRef'].clearFiles()
      })
  } else {
    cancelupload()
  }
}

function cancelupload() {
  showUpload.value = false
}

//跳转统计
function gotoStatistics() {
  router.push('grassrootsStatistical')
}

const selectRow = ref([])
const isDisabled = ref(true)
function handleSelectionChange(val) {
  if (val.length != 1) {
    isDisabled.value = true
    selectRow.value = {}
  } else {
    isDisabled.value = false
    selectRow.value = val[0]
  }
}

init()
</script>

<style scoped lang="scss"></style>
